package com.servicelive.service;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;

import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.servicelivedb.ServiceliveDB;
import com.servicelivedb.data.Customer;
import com.wavemaker.runtime.RuntimeAccess;
import com.wavemaker.runtime.javaservice.JavaServiceSuperClass;
import com.wavemaker.runtime.service.annotations.ExposeToClient;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.servicelive.ServiceLiveCommonService.OrderedItemDetails;
import com.servicelivedb.data.Block;
import com.servicelivedb.data.Door;
import com.servicelivedb.data.Items;
import com.servicelivedb.data.Order;
import com.servicelivedb.data.OrderItems; 

import org.apache.commons.io.IOUtils;

import sun.net.www.http.HttpClient;

/**
 * This is a client-facing service class.  All
 * public methods will be exposed to the client.  Their return
 * values and parameters will be passed to the client or taken
 * from the client, respectively.  This will be a singleton
 * instance, shared between all requests. 
 * 
 * To log, call the superclass method log(LOG_LEVEL, String) or log(LOG_LEVEL, String, Exception).
 * LOG_LEVEL is one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log level.
 * For info on these levels, look for tomcat/log4j documentation
 */
@ExposeToClient
public class MailSenderService extends JavaServiceSuperClass {
/* Pass in one of FATAL, ERROR, WARN,  INFO and DEBUG to modify your log level;
     *  recommend changing this to FATAL or ERROR before deploying.  For info on these levels, look for tomcat/log4j documentation
     */
    public MailSenderService() {
        super(INFO);
    }

    // Change these parameters to use your own email service!
    private static final String smtpHost = "smtp.gmail.com";
    private static final String smtpHostUser = "adisagar";
    private static final String smtpHostPassword = "AdityaPrasad";
    private static final String senderEmail = "adisagar@gmail.com";
      /* Pass in one of FATAL, ERROR, WARN,  INFO and DEBUG to modify your log level;
       *  recommend changing this to FATAL or ERROR before deploying.  For info on these levels, look for tomcat/log4j documentation
       */
     

    public String sendEmail(String fromEmailAddress, String toEmailAddress, 
	  String emailSubject, 
	  String emailMessage){ 
      try{

        // Use javamail api, set parameters from registration.properties file
        // set the session properties
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.required", "true");
        javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(props, null);
        
        // Create email message
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress(senderEmail));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmailAddress));
        message.setSubject("Order Confirmation");  
        message.setText("Your order has been placed");
        
        // Send smtp message
        Transport tr = mailSession.getTransport("smtp");
        tr.connect(smtpHost, 587, smtpHostUser, smtpHostPassword);
        message.saveChanges();
        tr.sendMessage(message, message.getAllRecipients());
        tr.close();
        
        return "Mail sent successfully.";

      } catch (MessagingException e) {
        log(ERROR, "Error in method sendEmailNotification: ", e);
        return "Error in method sendEmailNotification: " + e;
      }
    }
    
    public String sendEmailToVendor(String orderId){ 
    	ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");

      try{
    	  db.begin();
			System.out.println("orderId : " + orderId);
    	  Session session = db.getDataServiceManager().getSession();
    	  Order order = (Order) session.get(Order.class,Integer.parseInt(orderId));
    	  
    	  

    	  Customer vendor =  order.getCustomerByVendorId();
    	  Customer customer =  order.getCustomerByCustomerId();

    	  Block block = customer.getBlock();
    	  Door door = customer.getDoor();
    	  
    		Query query = session
					.createQuery(" from OrderItems orderItems where orderItems.order.orderId= :orderId");
			query.setBigInteger("orderId",BigInteger.valueOf(Integer.parseInt(orderId)));

			List orderList = query.list();   
			String itemDetails = "";
			BigDecimal totalPrice = new BigDecimal(0);
			for(int index = 0; index <orderList.size(); index++ )
			{ 
				OrderItems orderItem = (OrderItems) orderList.get(index);
				Items item = orderItem.getItems();
				itemDetails = itemDetails + ( index+1) + ". <b> " + item.getItemName() 
						 		+ "<br> Quantity : " + item.getQuantity()	
						 		+ "<br> Rs. " + orderItem.getPrice()
						 		+ "</b> <br>" ;
				totalPrice =orderItem.getPrice().add(totalPrice); //totalPrice +  orderItem.getPrice() ;
			}
			
			itemDetails = itemDetails + "<br><br> Total Price : Rs. " + totalPrice;
    	  
    	  // Use javamail api, set parameters from registration.properties file
          // set the session properties
          Properties props = System.getProperties();
          props.put("mail.smtp.starttls.enable", "true");
          props.put("mail.smtp.host", smtpHost);
          props.put("mail.smtp.port", "587");
          props.put("mail.smtp.auth", "true");
          props.put("mail.smtp.starttls.required", "true");
          javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(props, null);
          

          // Send smtp message
          Transport tr = mailSession.getTransport("smtp");
          tr.connect(smtpHost, 587, smtpHostUser, smtpHostPassword);
          
    	  
    	  String vendorEmailSubject = "Service Live : New Order"; 
    	  String vendorEmailMessage = "<b> You have got a new order. <br><br> <u> Order Details : </u> <br> Customer Name : " + customer.getName()
    			  	 + "<br> Order Id :" + orderId
    			     + "<br> Block number : " + block.getBlockName() 
    			     + "<br> Door Name : " + door.getDoorName()
    			     + "<br> Contact Number : " + customer.getPrimaryPhone()
    			     + "<br> <br> <b><u> Item Details </b></u>"
    			     + "<br>" + itemDetails
    			     + "<br> <br> <br> Regards "
    			     + "<br> Service Live,<br> Banglore"
    			     + "</b>";
    	  
      
        // Create email message
        MimeMessage messageVendor = new MimeMessage(mailSession);
        messageVendor.setFrom(new InternetAddress(senderEmail));
        messageVendor.addRecipient(Message.RecipientType.TO, new InternetAddress(vendor.getEmail()));
        messageVendor.setSubject(vendorEmailSubject);  
        messageVendor.setContent(vendorEmailMessage,"text/html");
        messageVendor.saveChanges();

		System.out.println("Sending mail to Vendor  : " + vendor.getEmail());
        tr.sendMessage(messageVendor, messageVendor.getAllRecipients());
        
        
        String customerEmailSubject = "Service Live : Order Placed"; 
        String customerEmailMessage = "<b> Your order has been placed successfully!." +
        		                      "<br> Order Id is " + orderId 
        		                      + "<br> <br> <b><u> Item Details </b></u>"
        		                      + "<br>" + itemDetails
        		                      + "<br> Vendor will get back to you shortly. </b>";
        
        
        MimeMessage messageCustomer = new MimeMessage(mailSession);
        messageCustomer.setFrom(new InternetAddress(senderEmail));
        messageCustomer.addRecipient(Message.RecipientType.TO, new InternetAddress(customer.getEmail()));
        messageCustomer.setSubject(customerEmailSubject);  
        messageCustomer.setContent(customerEmailMessage,"text/html");
       
        messageCustomer.saveChanges();

		System.out.println("Sending mail to customer  : " + customer.getEmail());
        tr.sendMessage(messageCustomer, messageCustomer.getAllRecipients());
        
        tr.close();
        db.commit();
        return "Mail sent successfully.";

      } catch (MessagingException e) {
    	  db.rollback();
        log(ERROR, "Error in method sendEmailNotification: ", e);
        return "Error in method sendEmailNotification: " + e;
      }
    }
    
    public void SendSms()
    {
    	
    	String endPoint="http://bulksms.mysmsmantra.com:8080/WebSMS/SMSAPI.jsp?username=adisagar&password=1262006954&sendername=adisagar&mobileno=8095504222&message=Hello";
    	//GetMethod get = new GetMethod("http://httpcomponents.apache.org");
    	// execute method and handle any error responses.
    	//...
    	//InputStream in = get.getResponseBodyAsStream();
    	// Process the data from the input stream.
    	//get.releaseConnection();
    	
    }
} 